import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_mine.dart';
import 'package:flutter_learn_vi/src/model/bloc_model.dart';
import 'package:flutter_learn_vi/src/model/user_model.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';

import 'mine_address_user_page.dart';
import 'mine_select_enum.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/17.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///

///代码清单
class MineSelectDepartmentPage extends StatefulWidget {
  final MineBean mineBean;
  final MineSelectType mineSelectType;

  const MineSelectDepartmentPage({
    Key key,
    @required this.mineBean,
    this.mineSelectType = MineSelectType.common,
  }) : super(key: key);

  @override
  _MineSelectDepartmentPageState createState() =>
      _MineSelectDepartmentPageState();
}

class _MineSelectDepartmentPageState extends State<MineSelectDepartmentPage>
    with BlocModel, UserModel {
  List<MineBeanDepartmentBean> _allLlist = [];
  List<MineBeanDepartmentBean> _themLlist = [];

  @override
  void initState() {
    super.initState();
    getMineDetails();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        //可滚动组件在滚动时会发送ScrollNotification类型的通知
        notificationPredicate: (ScrollNotification notifation) {
          //该属性包含当前ViewPort及滚动位置等信息
          ScrollMetrics scrollMetrics = notifation.metrics;
          if (scrollMetrics.minScrollExtent == 0) {
            return true;
          } else {
            return false;
          }
        },
        onRefresh: () async {
          await getMineDetails();
          return true;
        },
        child: NestedScrollView(
          body: buildGridView(),
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return [
              SliverAppBar(
                title: Text("矿通讯录"),
                pinned: true,
                expandedHeight: 124,
                flexibleSpace: FlexibleSpaceBar(
                  background: Container(
                    color: Colors.white,
                    padding: EdgeInsets.only(bottom: 12, left: 16, right: 16),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Container(
                          height: 40,
                          padding: EdgeInsets.only(left: 12, right: 12, top: 4),
                          decoration: BoxDecoration(
                              border: Border.all(
                                  color: Colors.blueGrey.withOpacity(0.6)),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(24))),
                          alignment: Alignment.center,
                          child: TextField(
                            onChanged: (String value) {
                              searchFunction(value);
                            },
                            decoration: InputDecoration(
                                hintText: "搜索", border: InputBorder.none),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              )
            ];
          },
        ),
      ),
    );
  }

  Widget buildGridView() {
    if (isLoading) {
      return Center(
        child: LoadingWidget(),
      );
    }
    if (_allLlist.length == 0) {
      return Center(
        child: NoDataWidget(
          clickCallBack: () {
            getMineDetails();
          },
        ),
      );
    }
    return ListView.builder(
      padding: EdgeInsets.only(top: 10),
      itemCount: _themLlist.length,
      itemBuilder: (BuildContext context, int index) {
        return buildListViewItemWidget(index);
      },
    );
  }

  Widget buildListViewItemWidget(int index) {
    MineBeanDepartmentBean departmentBean = _themLlist[index];
    return InkWell(
      onTap: () {
        NavigatorUtils.pushPage(
          context,
          MineSelectDepartmentUserPage(
            mineBean: widget.mineBean,
            departmentBean: departmentBean,
            mineSelectType: widget.mineSelectType,
          ),
          callback: (value) {
            if (value != null) {
              NavigatorUtils.pop(context, parameters: value);
            }
          },
        );
      },
      child: Container(
        margin: EdgeInsets.only(left: 14, right: 14, top: 10),
        padding: EdgeInsets.only(left: 20, top: 20, bottom: 20, right: 12),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(3))),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            buildImage(index),
            SizedBox(
              width: 18,
            ),
            Expanded(
              child: Text(
                "${departmentBean.department}",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  fontSize: 16,
                ),
              ),
            ),
            Icon(Icons.arrow_forward_ios_rounded)
          ],
        ),
      ),
    );
  }

  Widget buildImage(int index) {
    return Container(
      child: Text("${index + 1}"),
    );
  }

  void searchFunction(String title) {
    LogUtils.e("搜索 title $title");
    _themLlist.clear();
    if (title.trim().length == 0) {
      setState(() {
        _themLlist.addAll(_allLlist);
      });
    } else {
      _allLlist.forEach((element) {
        String name = element.department;
        if (name.contains(title)) {
          _themLlist.add(element);
        }
      });
    }
    setState(() {});
  }

  bool isLoading = true;

  Future<bool> getMineDetails() async {
    //获取
    _allLlist = await getMineDepartmentRequest(mineId: widget.mineBean.id);
    _themLlist = [];
    _themLlist.addAll(_allLlist);
    isLoading = false;
    if (!mounted) return true;
    setState(() {});
    return Future.value(true);
  }
}
